package com.lzp.java.concurrent.threadcore.stopthread;

import java.util.concurrent.TimeUnit;

/**
 * run方法中每次迭代都有sleep或者wait，不需要每次迭代都进行中断判断。有判断亦可
 *
 * @author lzp
 * @date 2020/01/31
 */
public class RightWayStopThreadRunWithSleepEachIterator {
    public static void main(String[] args) throws InterruptedException {
        Runnable task = () -> {
            int num = 0;
            try {
                // while (!Thread.currentThread().isInterrupted() && num <= 300) {
                while (num <= 300) {
                    System.out.println(num);
                    Thread.sleep(10);
                    // TimeUnit.NANOSECONDS.sleep(1); // 延时1ns
                    num++;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        Thread thread = new Thread(task);
        thread.start();
        Thread.sleep(500);
        thread.interrupt();
    }
}
